<!doctype html>



  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>






<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.0" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="iOS," />








  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.0" />






<meta name="description" content="前言 项目中数据的安全是非常重要的，2017年后苹果强制iOS开发者必须使用https，这在一定程度提高了项目的安全性，但仅仅靠https和post请求对数据安全的处理其实还是远远不够的。因此项目中我们还需要用到一些加密算法来保护数据。比如说在登录过程中我们会对密码进行MD5处理后再传输给服务器。因此趁有时间总结一下常见的数据加密算法。 数据安全简介 用户隐私数据不允许用明文在网络中传输 用户隐私">
<meta name="keywords" content="iOS">
<meta property="og:type" content="article">
<meta property="og:title" content="iOS数据安全浅谈">
<meta property="og:url" content="https://github.com/xiaoqiang051512/xiaoqiang051512.github.io/2017/06/28/iOS数据浅谈/index.html">
<meta property="og:site_name" content="小强5号">
<meta property="og:description" content="前言 项目中数据的安全是非常重要的，2017年后苹果强制iOS开发者必须使用https，这在一定程度提高了项目的安全性，但仅仅靠https和post请求对数据安全的处理其实还是远远不够的。因此项目中我们还需要用到一些加密算法来保护数据。比如说在登录过程中我们会对密码进行MD5处理后再传输给服务器。因此趁有时间总结一下常见的数据加密算法。 数据安全简介 用户隐私数据不允许用明文在网络中传输 用户隐私">
<meta property="og:image" content="http://oor0l2hfq.bkt.clouddn.com/2230763-803c71cbc7725637-2.png">
<meta property="og:updated_time" content="2017-06-30T07:04:39.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="iOS数据安全浅谈">
<meta name="twitter:description" content="前言 项目中数据的安全是非常重要的，2017年后苹果强制iOS开发者必须使用https，这在一定程度提高了项目的安全性，但仅仅靠https和post请求对数据安全的处理其实还是远远不够的。因此项目中我们还需要用到一些加密算法来保护数据。比如说在登录过程中我们会对密码进行MD5处理后再传输给服务器。因此趁有时间总结一下常见的数据加密算法。 数据安全简介 用户隐私数据不允许用明文在网络中传输 用户隐私">
<meta name="twitter:image" content="http://oor0l2hfq.bkt.clouddn.com/2230763-803c71cbc7725637-2.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    sidebar: {"position":"right","display":"always","offset":12,"offset_float":0,"b2t":false,"scrollpercent":false},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://github.com/xiaoqiang051512/xiaoqiang051512.github.io/2017/06/28/iOS数据浅谈/"/>





  <title> iOS数据安全浅谈 | 小强5号 </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?de5f7eecb9707639a092d57bccd58ae8";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>










  
  
    
  

  <div class="container sidebar-position-right page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">小强5号</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-ios,生活杂谈,其它"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archives"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-oc,swift,生活,其它"></i> <br />
            
            标签
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocapitalize="off" autocomplete="off" autocorrect="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <link itemprop="mainEntityOfPage" href="https://github.com/xiaoqiang051512/xiaoqiang051512.github.io/2017/06/28/iOS数据浅谈/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="刘志伟">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/uploads/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="小强5号">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                iOS数据安全浅谈
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-06-28T16:13:56+08:00">
                2017-06-28
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/OC/" itemprop="url" rel="index">
                    <span itemprop="name">OC</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    


    <div class="post-body han-init-context" itemprop="articleBody">

      
      

      
        <h3 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h3><p> 项目中数据的安全是非常重要的，2017年后苹果强制iOS开发者必须使用https，这在一定程度提高了项目的安全性，但仅仅靠https和post请求对数据安全的处理其实还是远远不够的。因此项目中我们还需要用到一些加密算法来保护数据。比如说在登录过程中我们会对密码进行MD5处理后再传输给服务器。因此趁有时间总结一下常见的数据加密算法。</p>
<h3 id="数据安全简介"><a href="#数据安全简介" class="headerlink" title="数据安全简介"></a>数据安全简介</h3><ul>
<li>用户隐私数据不允许用明文在网络中传输</li>
<li>用户隐私数据不允许用明文存储在本地</li>
<li>app代码安全，常见的用代码混淆、加密、加壳</li>
</ul>
<h3 id="数据加密准则"><a href="#数据加密准则" class="headerlink" title="数据加密准则"></a>数据加密准则</h3><ul>
<li>用Base64编码防止明文传输（数据体积会增加1/3）</li>
<li>对普通请求、返回数据，生成MD5校验（MD5中加入动态密钥），进行数据完整性（简单防篡改，安全性较低，优点：快速）校验</li>
<li>对于重要的数据用RSA签名，防止篡改</li>
<li>对于标记敏感的数据，比如密码、身份证号等敏感信息客户端用RSA签名后进行传输，服务器通过AES/DES加密返回</li>
<li>用https+ssl 进行双向验证 防止中间人攻击</li>
</ul>
<h3 id="常用加密方式简介"><a href="#常用加密方式简介" class="headerlink" title="常用加密方式简介"></a>常用加密方式简介</h3><h5 id="Https-ssl"><a href="#Https-ssl" class="headerlink" title="Https+ssl"></a>Https+ssl</h5><h6 id="https简介："><a href="#https简介：" class="headerlink" title="https简介："></a>https简介：</h6><p> HTTPS（全称：Hyper Text Transfer Protocol over Secure Socket Layer），是以安全为目标的HTTP通道，简单讲是HTTP的安全版，在HTTP下加入SSL层，HTTPS的安全基础是SSL，因此加密的详细内容就需要SSL。 它是一个URI scheme（抽象标识符体系），句法类同http:体系。用于安全的HTTP数据传输。URL表明它使用了HTTP，但HTTPS存在不同于HTTP的默认端口及一个加密/身份验证层（在HTTP与TCP之间）。2017年开始苹果要求app必须使用https。</p>
<h6 id="https与http的区别："><a href="#https与http的区别：" class="headerlink" title="https与http的区别："></a>https与http的区别：</h6><ol>
<li>https协议需要到ca申请证书，一般免费证书很少，需要交费</li>
<li>http是超文本传输协议，信息是明文传输，https 则是具有安全性的ssl加密传输协议</li>
<li>http和https使用的是完全不同的连接方式，用的端口也不一样，前者是80，后者是443</li>
<li>http的连接很简单，是无状态的；HTTPS协议是由SSL+HTTP协议构建的可进行加密传输、身份认证的网络协议，比http协议安全</li>
</ol>
<h6 id="代码实现"><a href="#代码实现" class="headerlink" title="代码实现"></a>代码实现</h6> <figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div></pre></td><td class="code"><pre><div class="line"> AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];</div><div class="line"></div><div class="line">// 更改解析方式（请求网页源码应使用原始解析）</div><div class="line">manager.responseSerializer = [AFHTTPResponseSerializer serializer];</div><div class="line"></div><div class="line">// 设置对证书的处理方式</div><div class="line">// 允许自签名证书，必须的</div><div class="line">manager.securityPolicy.allowInvalidCertificates = YES;</div><div class="line">// 是否验证域名的CN字段（不是必须的，但是如果写YES，则必须导入证书）</div><div class="line">manager.securityPolicy.validatesDomainName = NO;</div><div class="line"></div><div class="line">[manager GET:@&quot;https://kyfw.12306.cn/otn&quot; parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) &#123;</div><div class="line"></div><div class="line">    NSLog(@&quot;success---%@&quot;,[[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding]);</div><div class="line">&#125; failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) &#123;</div><div class="line"></div><div class="line">    NSLog(@&quot;error---%@&quot;,error);</div><div class="line">&#125;];</div></pre></td></tr></table></figure>
<h5 id="Base64"><a href="#Base64" class="headerlink" title="Base64"></a>Base64</h5><p>  Base64是基于64个可打印字符来便是二进制数据的表示方法。它通常用于储存、传输一些二进制数据编码方法。</p>
<h6 id="Base64原理"><a href="#Base64原理" class="headerlink" title="Base64原理"></a>Base64原理</h6><p> 它是用64个可打印字符表示二进制所有数据方法。由于2的6次方等于64，所以可以用每6个位元为一个单元，对应某个可打印字符。由于3个字节有24个位元，就可以刚好对应4个Base64单元，也就是说3个字节需要用到4个Base64的可打印字符来表示。在Base64中可打印的字符有A-Z、a-z、数字0-9，“+/”，就是这64个字符所对应的表如下</p>
<p> <img src="http://oor0l2hfq.bkt.clouddn.com/2230763-803c71cbc7725637-2.png" alt="ASSIC码"></p>
<h6 id="代码实现-1"><a href="#代码实现-1" class="headerlink" title="代码实现"></a>代码实现</h6><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div></pre></td><td class="code"><pre><div class="line"></div><div class="line">#pragma mark - base64编码和解码</div><div class="line">// 对一个字符串进行base64编码,并且返回</div><div class="line">- (NSString *)base64EncodeString</div><div class="line">&#123;</div><div class="line">    //1.先转换为二进制数据</div><div class="line">    NSData *data = [self dataUsingEncoding:NSUTF8StringEncoding];</div><div class="line">    </div><div class="line">    //2.对二进制数据进行base64编码,完成之后返回字符串</div><div class="line">    return [data base64EncodedStringWithOptions:0];</div><div class="line">&#125;</div><div class="line"></div><div class="line">// 对base64编码之后的字符串解码,并且返回</div><div class="line">-(NSString *)base64DecodeString</div><div class="line">&#123;</div><div class="line">    //注意:该字符串是base64编码后的字符串</div><div class="line">    //1.转换为二进制数据(完成了解码的过程)</div><div class="line">    NSData *data = [[NSData alloc]initWithBase64EncodedString:self options:0];</div><div class="line">    </div><div class="line">    //2.把二进制数据在转换为字符串</div><div class="line">    return [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];</div><div class="line">&#125;</div><div class="line"></div><div class="line">/*PC端编码解码</div><div class="line">编码：base64 123.png -o 123.txt</div><div class="line">解码：base64 123.txt -o test.png -D*/</div></pre></td></tr></table></figure>
<h5 id="MD5加密（信息摘要算法）"><a href="#MD5加密（信息摘要算法）" class="headerlink" title="MD5加密（信息摘要算法）"></a>MD5加密（信息摘要算法）</h5><h6 id="MD5简介"><a href="#MD5简介" class="headerlink" title="MD5简介"></a>MD5简介</h6><ul>
<li><p><strong>原理：</strong><br>MD5属于哈希算法之一，它能把任意一个长度的字节串变化成一定长度的十六进制的大整数，并且字符串的转换过程是不可逆的，不能通过加密结果反向推导原始内容，并且输出的值是唯一的。</p>
</li>
<li><p><strong> 特点：</strong></p>
<ul>
<li><p>压缩性：任意长度的数据算出的MD5值都是固定的。</p>
</li>
<li><p>抗修改性：对元数据进行任何改动，哪怕只修改一个字节所得MD5值都会有很大区别</p>
</li>
<li><p>弱抗碰撞 : 已知原数据和其 MD5 值,想找到一个具有相同 MD5 值的数据(即伪造数据)是非常困难的.</p>
</li>
</ul>
</li>
</ul>
<ul>
<li><p><strong> 应用：</strong></p>
<ul>
<li>一致性验证：MD5将整个文件当做一个大文本信息,通过不可逆的字符串变换算法,产生一个唯一的MD5信息摘要.就像每个人都有自己独一无二的指纹,MD5对任何文件产生一个独一无二的数字指纹.</li>
</ul>
<ul>
<li><p>数字签名</p>
</li>
<li><p>安全访问认证</p>
</li>
</ul>
</li>
</ul>
<ul>
<li><p><strong>增加MD5破解困难度</strong></p>
<pre><code>- 加盐：先明文加盐后再进行MD5,这个拼接进来的字符串可以稍微复杂点
</code></pre><ul>
<li><p>加密+乱序</p>
</li>
<li><p>乱序+加盐 并多次MD5</p>
</li>
<li><p>使用消息认证机制HMAC：给定一个”秘钥”，对明文进行加密，并且做”两次散列”！-&gt; 得到的结果，还是 32 个字符，相对安全</p>
</li>
</ul>
</li>
</ul>
<h6 id="代码实现-2"><a href="#代码实现-2" class="headerlink" title="代码实现"></a>代码实现</h6><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div><div class="line">52</div><div class="line">53</div><div class="line">54</div><div class="line">55</div><div class="line">56</div><div class="line">57</div><div class="line">58</div><div class="line">59</div><div class="line">60</div><div class="line">61</div><div class="line">62</div><div class="line">63</div><div class="line">64</div><div class="line">65</div><div class="line">66</div><div class="line">67</div><div class="line">68</div><div class="line">69</div><div class="line">70</div><div class="line">71</div><div class="line">72</div><div class="line">73</div><div class="line">74</div><div class="line">75</div><div class="line">76</div><div class="line">77</div><div class="line">78</div><div class="line">79</div><div class="line">80</div><div class="line">81</div><div class="line">82</div><div class="line">83</div><div class="line">84</div><div class="line">85</div><div class="line">86</div><div class="line">87</div><div class="line">88</div><div class="line">89</div><div class="line">90</div><div class="line">91</div><div class="line">92</div><div class="line">93</div><div class="line">94</div><div class="line">95</div><div class="line">96</div><div class="line">97</div><div class="line">98</div><div class="line">99</div><div class="line">100</div><div class="line">101</div><div class="line">102</div><div class="line">103</div><div class="line">104</div><div class="line">105</div><div class="line">106</div><div class="line">107</div><div class="line">108</div></pre></td><td class="code"><pre><div class="line">#pragma mark - 哈希(散列)函数</div><div class="line">- (void)md5 &#123;</div><div class="line">    // MD5</div><div class="line">    NSLog(@&quot;MD5加密--&gt;%@&quot;,[@&quot;123LN34*&quot; md5String]);</div><div class="line">    // MD5--&gt;598eb1a985449913bfb54ed6e0a58510</div><div class="line">    </div><div class="line">    // (明文+加盐)MD5</div><div class="line">    NSLog(@&quot;(明文+加盐)MD5--&gt;\n%@&quot;,[[@&quot;123LN&quot; stringByAppendingString:salt] md5String]);</div><div class="line">    </div><div class="line">    // 先加密+乱序</div><div class="line">    NSLog(@&quot;先加密+乱序--&gt;\n%@&quot;,[@&quot;123LN&quot; hmacMD5StringWithKey:@&quot;iOShangzhou&quot;]);</div><div class="line">    </div><div class="line">    // sha1对字符串加密</div><div class="line">    NSLog(@&quot;sha1对字符串加密--&gt;\n%@&quot;,[@&quot;123LN&quot; sha1String]);</div><div class="line">    </div><div class="line">    // sha256对字符串加密</div><div class="line">    NSLog(@&quot;sha256对字符串加密--&gt;\n%@&quot;,[@&quot;123LN&quot; sha256String]);</div><div class="line">    </div><div class="line">    // sha512对字符串加密</div><div class="line">    NSLog(@&quot;sha512对字符串加密--&gt;\n%@&quot;,[@&quot;123LN&quot; sha1String]);</div><div class="line">&#125;</div><div class="line"></div><div class="line">#pragma mark - 字符串加密</div><div class="line"></div><div class="line">- (NSString *)md5String</div><div class="line">&#123;</div><div class="line">    const char *str = self.UTF8String;</div><div class="line">    uint8_t buffer[CC_MD5_DIGEST_LENGTH];</div><div class="line">    </div><div class="line">    CC_MD5(str, (CC_LONG)strlen(str), buffer);</div><div class="line">    </div><div class="line">    return [self stringFromBytes:buffer length:CC_MD5_DIGEST_LENGTH];</div><div class="line">&#125;</div><div class="line"></div><div class="line">- (NSString *)sha1String</div><div class="line">&#123;</div><div class="line">    const char *str = self.UTF8String;</div><div class="line">    uint8_t buffer[CC_SHA1_DIGEST_LENGTH];</div><div class="line">    </div><div class="line">    CC_SHA1(str, (CC_LONG)strlen(str), buffer);</div><div class="line">    </div><div class="line">    return [self stringFromBytes:buffer length:CC_SHA1_DIGEST_LENGTH];</div><div class="line">&#125;</div><div class="line"></div><div class="line">- (NSString *)sha256String</div><div class="line">&#123;</div><div class="line">    const char *str = self.UTF8String;</div><div class="line">    uint8_t buffer[CC_SHA256_DIGEST_LENGTH];</div><div class="line">    </div><div class="line">    CC_SHA256(str, (CC_LONG)strlen(str), buffer);</div><div class="line">    </div><div class="line">    return [self stringFromBytes:buffer length:CC_SHA256_DIGEST_LENGTH];</div><div class="line">&#125;</div><div class="line"></div><div class="line">- (NSString *)sha512String</div><div class="line">&#123;</div><div class="line">    const char *str = self.UTF8String;</div><div class="line">    uint8_t buffer[CC_SHA512_DIGEST_LENGTH];</div><div class="line">    </div><div class="line">    CC_SHA512(str, (CC_LONG)strlen(str), buffer);</div><div class="line">    </div><div class="line">    return [self stringFromBytes:buffer length:CC_SHA512_DIGEST_LENGTH];</div><div class="line">&#125;</div><div class="line"></div><div class="line">#pragma mark - HMAC 字符串加密</div><div class="line">- (NSString *)hmacMD5StringWithKey:(NSString *)key</div><div class="line">&#123;</div><div class="line">    const char *keyData = key.UTF8String;</div><div class="line">    const char *strData = self.UTF8String;</div><div class="line">    uint8_t buffer[CC_MD5_DIGEST_LENGTH];</div><div class="line">    </div><div class="line">    CCHmac(kCCHmacAlgMD5, keyData, strlen(keyData), strData, strlen(strData), buffer);</div><div class="line">    </div><div class="line">    return [self stringFromBytes:buffer length:CC_MD5_DIGEST_LENGTH];</div><div class="line">&#125;</div><div class="line"></div><div class="line">- (NSString *)hmacSHA1StringWithKey:(NSString *)key</div><div class="line">&#123;</div><div class="line">    const char *keyData = key.UTF8String;</div><div class="line">    const char *strData = self.UTF8String;</div><div class="line">    uint8_t buffer[CC_SHA1_DIGEST_LENGTH];</div><div class="line">    </div><div class="line">    CCHmac(kCCHmacAlgSHA1, keyData, strlen(keyData), strData, strlen(strData), buffer);</div><div class="line">    </div><div class="line">    return [self stringFromBytes:buffer length:CC_SHA1_DIGEST_LENGTH];</div><div class="line">&#125;</div><div class="line"></div><div class="line">- (NSString *)hmacSHA256StringWithKey:(NSString *)key</div><div class="line">&#123;</div><div class="line">    const char *keyData = key.UTF8String;</div><div class="line">    const char *strData = self.UTF8String;</div><div class="line">    uint8_t buffer[CC_SHA256_DIGEST_LENGTH];</div><div class="line">    </div><div class="line">    CCHmac(kCCHmacAlgSHA256, keyData, strlen(keyData), strData, strlen(strData), buffer);</div><div class="line">    </div><div class="line">    return [self stringFromBytes:buffer length:CC_SHA256_DIGEST_LENGTH];</div><div class="line">&#125;</div><div class="line"></div><div class="line">- (NSString *)hmacSHA512StringWithKey:(NSString *)key</div><div class="line">&#123;</div><div class="line">    const char *keyData = key.UTF8String;</div><div class="line">    const char *strData = self.UTF8String;</div><div class="line">    uint8_t buffer[CC_SHA512_DIGEST_LENGTH];</div><div class="line">    </div><div class="line">    CCHmac(kCCHmacAlgSHA512, keyData, strlen(keyData), strData, strlen(strData), buffer);</div><div class="line">    </div><div class="line">    return [self stringFromBytes:buffer length:CC_SHA512_DIGEST_LENGTH];</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h5 id="AES、DES"><a href="#AES、DES" class="headerlink" title="AES、DES"></a>AES、DES</h5><h6 id="对称加密的特点："><a href="#对称加密的特点：" class="headerlink" title="对称加密的特点："></a>对称加密的特点：</h6><ul>
<li>加密和解密过程中都是用的同一个密匙</li>
</ul>
<ul>
<li><p>加密和解密都是可逆的</p>
</li>
<li><p>加密过程是先加密再进行Base64码，解密过程先Base64解码再解密</p>
</li>
</ul>
<h6 id="代码实现-3"><a href="#代码实现-3" class="headerlink" title="代码实现"></a>代码实现</h6>  <figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div><div class="line">52</div><div class="line">53</div><div class="line">54</div><div class="line">55</div><div class="line">56</div><div class="line">57</div><div class="line">58</div><div class="line">59</div><div class="line">60</div><div class="line">61</div><div class="line">62</div><div class="line">63</div><div class="line">64</div><div class="line">65</div><div class="line">66</div><div class="line">67</div><div class="line">68</div><div class="line">69</div><div class="line">70</div><div class="line">71</div><div class="line">72</div><div class="line">73</div><div class="line">74</div><div class="line">75</div><div class="line">76</div><div class="line">77</div><div class="line">78</div><div class="line">79</div><div class="line">80</div><div class="line">81</div><div class="line">82</div><div class="line">83</div></pre></td><td class="code"><pre><div class="line">  -(void)AES</div><div class="line">&#123;</div><div class="line">    // encryWithPublicKey</div><div class="line">    NSString *str = [AES encrypt:@&quot;LN123&quot; keyString:@&quot;SDTUJZLI&quot;];</div><div class="line">    NSLog(@&quot;AES公钥加密数据--&gt;\n%@&quot;,str);</div><div class="line">    </div><div class="line">    // decryWithPriviteKey</div><div class="line">    NSString *str1 = [AES decrypt:str keyString:@&quot;SDTUJZLI&quot;];</div><div class="line">    NSLog(@&quot;AES私钥解密数据--&gt;\n%@&quot;,str1);</div><div class="line">&#125;</div><div class="line"></div><div class="line"></div><div class="line">-(void)DES</div><div class="line">&#123;    </div><div class="line">    NSString *str = [DES3Util encryptUseDES:@&quot;LN123&quot; keyString:@&quot;syh&quot;];</div><div class="line">    NSLog(@&quot;DES公钥加密数据--&gt;\n%@&quot;,str);</div><div class="line">    </div><div class="line">    NSString *str1 = [DES3Util decryptUseDES:str keyString:@&quot;syh&quot;];</div><div class="line">    NSLog(@&quot;DES私钥解密数据--&gt;\n%@&quot;,str1);</div><div class="line">&#125;</div><div class="line"></div><div class="line">// AES加密字符串并返回base64编码字符串</div><div class="line">+ (NSString *)encrypt:(NSString *)string keyString:(NSString *)keyString &#123;</div><div class="line">  NSData *encryptedData = [[string dataUsingEncoding:NSUTF8StringEncoding] AES256EncryptedDataUsingKey:[[keyString dataUsingEncoding:NSUTF8StringEncoding] SHA256Hash] error:nil];</div><div class="line">  NSString *base64EncodedString = [NSString base64StringFromData:encryptedData length:[encryptedData length]];</div><div class="line">  return base64EncodedString;</div><div class="line">&#125;</div><div class="line"></div><div class="line">// AES解密字符串</div><div class="line">+ (NSString *)decrypt:(NSString *)base64EncodedString keyString:(NSString *)keyString &#123;</div><div class="line">  NSData *encryptedData = [NSData base64DataFromString:base64EncodedString];</div><div class="line">  NSData *decryptedData = [encryptedData decryptedAES256DataUsingKey:[[keyString dataUsingEncoding:NSUTF8StringEncoding] SHA256Hash] error:nil];</div><div class="line">  return [[NSString alloc] initWithData:decryptedData encoding:NSUTF8StringEncoding];</div><div class="line">&#125;</div><div class="line"></div><div class="line">// Des加密</div><div class="line">+(NSString *) encryptUseDES:(NSString *)string keyString:(NSString *)keyString</div><div class="line">&#123;</div><div class="line">    </div><div class="line">    NSString *ciphertext = nil;</div><div class="line">    NSData *textData = [string dataUsingEncoding:NSUTF8StringEncoding];</div><div class="line">    NSUInteger dataLength = [textData length];</div><div class="line">    unsigned char buffer[1024];</div><div class="line">    memset(buffer, 0, sizeof(char));</div><div class="line">    size_t numBytesEncrypted = 0;</div><div class="line">    CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmDES,</div><div class="line">                                          kCCOptionPKCS7Padding,</div><div class="line">                                          [keyString UTF8String], kCCKeySizeDES,</div><div class="line">                                          iv,</div><div class="line">                                          [textData bytes], dataLength,</div><div class="line">                                          buffer, 1024,</div><div class="line">                                          &amp;numBytesEncrypted);</div><div class="line">    if (cryptStatus == kCCSuccess) &#123;</div><div class="line">        NSData *data = [NSData dataWithBytes:buffer length:(NSUInteger)numBytesEncrypted];</div><div class="line">        ciphertext = [GTMBase64 stringByEncodingData:data];</div><div class="line">    &#125;</div><div class="line">    return ciphertext;</div><div class="line">&#125;</div><div class="line"></div><div class="line"></div><div class="line"></div><div class="line">// Des解密</div><div class="line">+(NSString *)decryptUseDES:(NSString *)base64EncodedString keyString:(NSString *)keyString</div><div class="line">&#123;</div><div class="line">    NSString *plaintext = nil;</div><div class="line">    NSData *cipherdata = [GTMBase64 decodeString:base64EncodedString];</div><div class="line">    unsigned char buffer[1024];</div><div class="line">    memset(buffer, 0, sizeof(char));</div><div class="line">    size_t numBytesDecrypted = 0;</div><div class="line">    CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, kCCAlgorithmDES,</div><div class="line">                                          kCCOptionPKCS7Padding,</div><div class="line">                                          [keyString UTF8String], kCCKeySizeDES,</div><div class="line">                                          iv,</div><div class="line">                                          [cipherdata bytes], [cipherdata length],</div><div class="line">                                          buffer, 1024,</div><div class="line">                                          &amp;numBytesDecrypted);</div><div class="line">    if(cryptStatus == kCCSuccess)</div><div class="line">    &#123;</div><div class="line">        NSData *plaindata = [NSData dataWithBytes:buffer length:(NSUInteger)numBytesDecrypted];</div><div class="line">        plaintext = [[NSString alloc]initWithData:plaindata encoding:NSUTF8StringEncoding];</div><div class="line">    &#125;</div><div class="line">    return plaintext;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h5 id="RSA"><a href="#RSA" class="headerlink" title="RSA"></a>RSA</h5><h6 id="RSA简介"><a href="#RSA简介" class="headerlink" title="RSA简介"></a>RSA简介</h6><ul>
<li><p>使用公匙加密，私匙解密</p>
</li>
<li><p>使用私匙加密，公匙解密</p>
</li>
<li><p>公匙是公开的，私匙是保密的</p>
</li>
<li><p>加密安全，但性能不好</p>
</li>
</ul>
<h6 id="如何在生成公匙-私匙"><a href="#如何在生成公匙-私匙" class="headerlink" title="如何在生成公匙 私匙"></a>如何在生成公匙 私匙</h6><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div></pre></td><td class="code"><pre><div class="line"># MAC上生成公钥、私钥的方法</div><div class="line"> @code</div><div class="line"> 1.打开终端，切换到自己想输出的文件夹下</div><div class="line"> 2.输入指令:openssl（openssl是生成各种秘钥的工具，mac已经嵌入)</div><div class="line"> 3.输入指令:genrsa -out rsa_private_key.pem 1024 (生成私钥，java端使用的)</div><div class="line"> 4.输入指令:rsa -in rsa_private_key.pem -out rsa_public_key.pem -pubout (生成公钥)</div><div class="line"> 5.输入指令:pkcs8 -topk8 -in rsa_private_key.pem -out pkcs8_rsa_private_key.pem -nocrypt(私钥转格式，在ios端使用私钥解密时用这个私钥)</div><div class="line"> 注意:在MAC上生成三个.pem格式的文件，一个公钥，两个私钥，都可以在终端通过指令vim xxx.pem 打开，里面是字符串，第三步生成的私钥是java端用来解密数据的，第五步转换格式的私钥iOS端可以用来调试公钥、私钥解密（因为私钥不留在客户端）</div><div class="line"> iOS端公钥加密私钥解密、java端公钥加密私钥解密，java端私钥加密公钥解密都容易做到，iOS不能私钥加密公钥解密，只能用于验签</div></pre></td></tr></table></figure>
<h6 id="代码实现-4"><a href="#代码实现-4" class="headerlink" title="代码实现"></a>代码实现</h6> <figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div></pre></td><td class="code"><pre><div class="line"> @interface RSAUtil : UIViewController</div><div class="line"></div><div class="line">// 公钥加密时调用类方法：</div><div class="line">+ (NSString *)encryptString:(NSString *)str publicKey:(NSString *)pubKey;</div><div class="line">+ (NSData *)encryptData:(NSData *)data publicKey:(NSString *)pubKey;</div><div class="line"></div><div class="line">// 私钥解密时调用类方法</div><div class="line">+ (NSString *)decryptString:(NSString *)str privateKey:(NSString *)privKey;</div><div class="line">+ (NSData *)decryptData:(NSData *)data privateKey:(NSString *)privKey;</div></pre></td></tr></table></figure>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/iOS/" rel="tag"># iOS</a>
          
        </div>
      

      
        
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2017/06/28/OC常用方法/" rel="prev" title="OC常用方法">
                OC常用方法 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/uploads/images/avatar.jpg"
               alt="刘志伟" />
          <p class="site-author-name" itemprop="name">刘志伟</p>
           
              <p class="site-description motion-element" itemprop="description">人间正道是沧桑</p>
          
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/archives">
                <span class="site-state-item-count">4</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/categories/index.html">
                <span class="site-state-item-count">2</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-tags">
              <a href="/tags/index.html">
                <span class="site-state-item-count">2</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
        </div>

        
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#前言"><span class="nav-number">1.</span> <span class="nav-text">前言</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#数据安全简介"><span class="nav-number">2.</span> <span class="nav-text">数据安全简介</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#数据加密准则"><span class="nav-number">3.</span> <span class="nav-text">数据加密准则</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#常用加密方式简介"><span class="nav-number">4.</span> <span class="nav-text">常用加密方式简介</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#Https-ssl"><span class="nav-number">4.0.1.</span> <span class="nav-text">Https+ssl</span></a><ol class="nav-child"><li class="nav-item nav-level-6"><a class="nav-link" href="#https简介："><span class="nav-number">4.0.1.1.</span> <span class="nav-text">https简介：</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#https与http的区别："><span class="nav-number">4.0.1.2.</span> <span class="nav-text">https与http的区别：</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#代码实现"><span class="nav-number">4.0.1.3.</span> <span class="nav-text">代码实现</span></a></li></ol></li><li class="nav-item nav-level-5"><a class="nav-link" href="#Base64"><span class="nav-number">4.0.2.</span> <span class="nav-text">Base64</span></a><ol class="nav-child"><li class="nav-item nav-level-6"><a class="nav-link" href="#Base64原理"><span class="nav-number">4.0.2.1.</span> <span class="nav-text">Base64原理</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#代码实现-1"><span class="nav-number">4.0.2.2.</span> <span class="nav-text">代码实现</span></a></li></ol></li><li class="nav-item nav-level-5"><a class="nav-link" href="#MD5加密（信息摘要算法）"><span class="nav-number">4.0.3.</span> <span class="nav-text">MD5加密（信息摘要算法）</span></a><ol class="nav-child"><li class="nav-item nav-level-6"><a class="nav-link" href="#MD5简介"><span class="nav-number">4.0.3.1.</span> <span class="nav-text">MD5简介</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#代码实现-2"><span class="nav-number">4.0.3.2.</span> <span class="nav-text">代码实现</span></a></li></ol></li><li class="nav-item nav-level-5"><a class="nav-link" href="#AES、DES"><span class="nav-number">4.0.4.</span> <span class="nav-text">AES、DES</span></a><ol class="nav-child"><li class="nav-item nav-level-6"><a class="nav-link" href="#对称加密的特点："><span class="nav-number">4.0.4.1.</span> <span class="nav-text">对称加密的特点：</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#代码实现-3"><span class="nav-number">4.0.4.2.</span> <span class="nav-text">代码实现</span></a></li></ol></li><li class="nav-item nav-level-5"><a class="nav-link" href="#RSA"><span class="nav-number">4.0.5.</span> <span class="nav-text">RSA</span></a><ol class="nav-child"><li class="nav-item nav-level-6"><a class="nav-link" href="#RSA简介"><span class="nav-number">4.0.5.1.</span> <span class="nav-text">RSA简介</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#如何在生成公匙-私匙"><span class="nav-number">4.0.5.2.</span> <span class="nav-text">如何在生成公匙 私匙</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#代码实现-4"><span class="nav-number">4.0.5.3.</span> <span class="nav-text">代码实现</span></a></li></ol></li></ol></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2017</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">刘志伟</span>
</div>


<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Mist
  </a>
</div>


        

        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.0"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.0"></script>



  


  




	





  





  





  






  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length == 0) {
      search_path = "search.xml";
    }
    var path = "/" + search_path;
    // monitor main search box;

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.popup').toggle();
    }
    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';
      $.ajax({
        url: path,
        dataType: "xml",
        async: true,
        success: function( xmlResponse ) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = $( "entry", xmlResponse ).map(function() {
            return {
              title: $( "title", this ).text(),
              content: $("content",this).text(),
              url: $( "url" , this).text()
            };
          }).get();
          var $input = document.getElementById(search_id);
          var $resultContent = document.getElementById(content_id);
          $input.addEventListener('input', function(){
            var matchcounts = 0;
            var str='<ul class=\"search-result-list\">';
            var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
            $resultContent.innerHTML = "";
            if (this.value.trim().length > 1) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var content_index = [];
                var data_title = data.title.trim().toLowerCase();
                var data_content = data.content.trim().replace(/<[^>]+>/g,"").toLowerCase();
                var data_url = decodeURIComponent(data.url);
                var index_title = -1;
                var index_content = -1;
                var first_occur = -1;
                // only match artiles with not empty titles and contents
                if(data_title != '') {
                  keywords.forEach(function(keyword, i) {
                    index_title = data_title.indexOf(keyword);
                    index_content = data_content.indexOf(keyword);
                    if( index_title >= 0 || index_content >= 0 ){
                      isMatch = true;
                      if (i == 0) {
                        first_occur = index_content;
                      }
                    }

                  });
                }
                // show search results
                if (isMatch) {
                  matchcounts += 1;
                  str += "<li><a href='"+ data_url +"' class='search-result-title'>"+ data_title +"</a>";
                  var content = data.content.trim().replace(/<[^>]+>/g,"");
                  if (first_occur >= 0) {
                    // cut out 100 characters
                    var start = first_occur - 20;
                    var end = first_occur + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if(start == 0){
                      end = 50;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    var match_content = content.substring(start, end);
                    // highlight all keywords
                    keywords.forEach(function(keyword){
                      var regS = new RegExp(keyword, "gi");
                      match_content = match_content.replace(regS, "<b class=\"search-keyword\">"+keyword+"</b>");
                    });

                    str += "<p class=\"search-result\">" + match_content +"...</p>"
                  }
                  str += "</li>";
                }
              })};
            str += "</ul>";
            if (matchcounts == 0) { str = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>' }
            if (keywords == "") { str = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>' }
            $resultContent.innerHTML = str;
          });
          proceedsearch();
        }
      });}

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched == false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(function(e){
      $('.popup').hide();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    });
    $('.popup').click(function(e){
      e.stopPropagation();
    });
  </script>





  

  

  

  

  

</body>
</html>
